<?php

namespace Iwester\Http\Controllers\Admin\Zixun;

use Illuminate\Support\Facades\Auth;
use Iwester\Http\Controllers\Admin\BaseController;
use App\Console\Commands\SiteMap;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Iwester\Http\Model\Article\Article;
use Iwester\Http\Model\Article\ArticleComment;
use Iwester\Http\Model\Article\ArticleCommentLike;
use Iwester\Http\Model\Article\ArticleContent;
use Iwester\Http\Model\Article\ArticleLike;
use Iwester\Http\Model\Article\ArticleTag;
use Iwester\Http\Model\Config\SiteConfig;
use Monolog\Handler\IFTTTHandler;
use Symfony\Component\Translation\Tests\Writer\BackupDumper;
use View;
use Iwester\Http\Model\Article\ArticleCategory;


class AdminArticleController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * 资讯 - 文章列表
     * @return Response
     */
    public function article(Request $request)
    {
        # enable:公开  private:隐私  audit:审核  deleted:回收站
        $type = $request->get('type', 'all');
        $category_id = $request->get('category_id', false);
        $title = $request->get('title', false);
        $pageSize = 10;
        $whereArr = [];
        if ($category_id) $whereArr['article_category_id'] = $category_id;
        if ($title) $whereArr[] = ['title', 'like', '%' . $title . '%'];
        switch ($type) {
            case 'enable':
                $whereArr['publish_status'] = Article::PUBLISH;
                $articles = Article::getArticleData($whereArr, [['id' => 'desc']], $pageSize, true);
                break;
            case 'private':
                $whereArr['publish_status'] = Article::DRAFT;
                $articles = Article::getArticleData($whereArr, [['id' => 'desc']], $pageSize, true);
                break;
            case 'audit':
                $whereArr[] = ['audit_status', '=', 0];
                $articles = Article::getArticleData($whereArr, [['id' => 'desc']], $pageSize, true);
                break;
            case 'deleted':
                $articles = Article::orderBy('id', 'desc')->onlyTrashed();
                if ($whereArr) $articles->where($whereArr);
                $articles = $articles->paginate($pageSize);
                break;
            default:
                $articles = Article::getArticleData($whereArr, [['id' => 'desc']], $pageSize, true, [], true);
                break;
        }

        $typeCount = [
            'all' => ['全部', Article::withTrashed()->count()],
            'enable' => ['公开', Article::where('publish_status', Article::PUBLISH)->count()],
            'private' => ['隐私', Article::where('publish_status', Article::DRAFT)->count()],
            'audit'=> ['待审核', Article::where('audit_status', '=', 0)->count()],
            'deleted' => ['回收站', Article::onlyTrashed()->count()],
        ];
        $categories = ArticleCategory::allCategory();
        return view('iwester::admin.zixun.article.article', [
            'typeCount' => $typeCount,
            'articles' => $articles,
            'categories' => $categories,
            'type' => $type,
            'params' => $request->all()
        ]);
    }

    /**
     * 添加 - 编辑文章
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id = 0)
    {
        $tags = ArticleTag::getTags();
        $categories = ArticleCategory::allCategory();
        $article = $id ? Article::with(['articleContent', 'tags'])->where('id', $id)->first() : null;
        return view('iwester::admin.zixun.article.edit', [
            'categories' => $categories,
            'article' => $article,
            'tags' => $tags
        ]);
    }

    /**
     * 保存文章
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        try {
            \DB::beginTransaction();
            $id = $request->input('id', false);
            $articleParam = $request->get('article', []);
            $contentParam = $request->get('content', []);
            $tags = $request->get('tags', false);
            if (!isset($articleParam['publish_status'])) $articleParam['publish_status'] = 0;
            if ($id) {
                $article = Article::find($id);
                $article->update($articleParam);
                ArticleContent::where('article_id', $id)->update($contentParam);
            } else {
                $articleParam['published_at'] = date('Y-m-d');
                $article = Article::create($articleParam);
                $contentParam['article_id'] = $article->id;
                if (!$this->siteConfig->on_article_audit) {
                    $contentParam['audit_status'] = 1;
                }
                ArticleContent::create($contentParam);
            }
            if ($tags) $article->tags()->sync(json_decode($tags, true));
            \DB::commit();
            return redirect(route('zixun.article'));
        } catch (\Exception $e) {
            \DB::rollBack();
            return redirect()->route('zixun.article')->with('errors', ['系统错误，保存失败']);
        }
    }

    /**
     * 删除文章
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function destroy($id)
    {
        try {
            \DB::beginTransaction();
            $article = Article::find($id);
            if ($article) {
                $article->delete();
            } else {
                Article::where('id', $id)->forceDelete();
            }
            \DB::commit();
            return ['code' => 200, 'message' => '删除成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }

    /**
     * 恢复文章
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function recover($id)
    {
        try {
            \DB::beginTransaction();
            Article::where('id', $id)->restore();
            \DB::commit();
            return ['code' => 200, 'message' => '恢复文章成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }

    /**
     * 修改置顶状态
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function changeTop(Request $request, $id)
    {
        try {
            \DB::beginTransaction();
            $type = $request->get('type', false);
            $article = Article::find($id);
            $article->is_top = $type;
            $article->save();
            \DB::commit();
            return ['code' => 200, 'message' => '操作成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }

    /**
     * 修改文章审核状态
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function changeAudit(Request $request)
    {
        try {
            \DB::beginTransaction();
            $type = $request->get('type', false);
            $ids = $request->get('ids', false);
            $ids = json_decode($ids, true);
            Article::whereIn('id', $ids)->update(['audit_status'=> $type]);
            \DB::commit();
            return ['code' => 200, 'message' => '操作成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }

    /**
     * 文章点赞
     * @param $id
     * @return array
     */
    public function articleZan($id)
    {
        try {
            \DB::beginTransaction();
            $article = Article::find($id);
            if (!$article) return ['code' => 201, 'message' => '文章不存在'];
            $exites = ArticleLike::where(['article_id'=> $id, 'like_user'=> Auth::id()])->first();
            if ($exites) return ['code' => 201, 'message' => '已点赞~'];
            ArticleLike::store($id, Auth::id());
            \DB::commit();
            return ['code' => 200, 'message' => '已点赞~'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }

    /**
     * 文章评论点赞
     * @param $id
     * @return array
     */
    public function commentZan($id)
    {
        try {
            \DB::beginTransaction();
            $articleComment = ArticleComment::find($id);
            if (!$articleComment) return ['code' => 201, 'message' => '评论不存在'];
            $exites = ArticleCommentLike::where(['article_comment_id'=> $id, 'like_user'=> Auth::id()])->first();
            if ($exites) return ['code' => 201, 'message' => '已点赞~'];
            $articleCommentLike = ArticleCommentLike::store($articleComment->article_id, $id, Auth::id());
            \DB::commit();
            return ['code' => 200, 'message' => '已点赞~'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }

    /**
     * 文章 提交评论
     * @param $id
     * @return array
     */
    public function commentStore(Request $request)
    {
        try {
            \DB::beginTransaction();
            $data = $request->get('comment', false);
            if (!$data) return ['code' => 201, 'message' => '参数异常'];
            if (!$data['comment_content']) return ['code' => 201, 'message' => '评论不能为空'];
            $article = Article::find($data['article_id']);
            if (!$article) return ['code' => 201, 'message' => '文章已被删除'];
            // 敏感词判断
            $sensitiveWord = SiteConfig::sensitiveWord($this->siteConfig->sensitive_word, $data['comment_content']);
            if ($sensitiveWord !== false){
                return ['code' => 201, 'message' => '评论中包含敏感词“'.$sensitiveWord.'"'];
            }
            $data['comment_user'] = Auth::id();
            # 如果开启评论审核模式
            if ($this->siteConfig->on_article_comment_audit == 1){
                $data['audit_status'] = ArticleComment::AUDIT_WAIT;
            }
            ArticleComment::create($data);
            \DB::commit();
            # 如果开启评论审核模式 返回json
            if ($this->siteConfig->on_article_comment_audit == 1){
                return ['code' => 200, 'message' => '评论提交成功，将在审核通过后展示'];
            }
            $comments = ArticleComment::with(['commentUser', 'commentToUser', 'commentZan', 'subComment'=> function($query){
                $query->with(['commentUser', 'commentToUser', 'commentZan']);
            }])->where(['comment_id'=> 0, 'article_id'=> $article->id])->orderBy('created_at', 'desc')->get();
            return view('site.article.comment.comment', ['comments'=> $comments, 'article'=> $article]);
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }
}
